package org.deaboway.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.view.View;

public class GameView extends View implements Runnable {

    private Shape shape;
    private Drawable d;

    public GameView(Context context) {
	super(context);
	d = context.getResources().getDrawable(R.drawable.icon);
	shape = ShapeFactory.getShape();
	new Thread(this).start();
	this.setFocusable(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
	super.onDraw(canvas);

	shape.drawMe(canvas, d);
	// Paint paint = new Paint();
	// paint.setColor(Color.RED);
	// canvas.drawRect(20, 20, 100, 100, paint);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

	switch (keyCode) {
	case KeyEvent.KEYCODE_DPAD_UP:
	    shape.rotate();
	    break;
	case KeyEvent.KEYCODE_DPAD_DOWN:
	    if (shape.checkBound(Shape.DOWN))
		shape.moveDown();
	    break;
	case KeyEvent.KEYCODE_DPAD_LEFT:
	    if (shape.checkBound(Shape.LEFT))
		shape.moveLeft();
	    break;
	case KeyEvent.KEYCODE_DPAD_RIGHT:
	    if (shape.checkBound(Shape.RIGHT))
		shape.moveRight();
	    break;
	default:
	    break;
	}
	return super.onKeyDown(keyCode, event);
    }

    public void run() {

	while (true) {
	    if (shape.checkBound(Shape.DOWN))
		shape.moveDown();
	    postInvalidate();
	    try {
		Thread.sleep(1000);
	    } catch (InterruptedException e) {
		e.printStackTrace();
	    }
	}
    }

}
